<?php

namespace Home\Controller;
use Home\Org\Util\Sqlserver;
/**
 * 售前 售后服务
 * @author dem
 *
 */
class SaleController extends HomeController {
    
    /**
     * 售前
     */
    function getdataAjax(){
        $this->initialize();
        $orderId = I('orderId');
        $sql = "SELECT
	CAST (
		ROW_NUMBER () OVER (ORDER BY t10.U_DocDate) AS nvarchar
	) LineId,
	t10.*
FROM
	(
		SELECT DISTINCT
			t10.U_CardCode,
			t10.U_CardName,
			t11.U_OrderId,
			t11.U_Cstname,
			t11.U_Phone,
			t11.U_DocDate,
			t11.U_ItemCode,
			t11.U_ItemName,
			t11.U_CitemCd,
			t11.U_CitemNm,
			t11.U_Color,
			t11.U_Address,
			t11.U_City,
			t11.U_Type
		FROM
			[@TI_Z0080] t10
		INNER JOIN [@TI_Z0081] t11 ON t10.DocEntry = t11.DocEntry
		WHERE
			t11.U_OStatus <> '5'
		AND t11.U_OrderId LIKE '%{$orderId}%'
	) t10";
        
        $db = new \Sqlserver(); 
        $db->connent();
        if(!I('fmjson')){
        $data= $db->query($sql);
        //售前信息
        $preSql = "SELECT TOP 10 t.U_Suggest, t.DocEntry,t2.U_ProSts, U_AccuName ,U_ItemCode ,U_ItemName ,U_AccuDate ,U_AccuTime ,U_Phone ,U_Cstname ,U_AccuQDtl ,U_Address ,U_Qsummary ,U_Memo ,U_UserCode ,U_UserName  ,U_ProEndDate,U_ProEndTime ,U_AccuQDt2,U_Dealer,U_DealerName from [@TI_Z0220] as t  INNER JOIN [@TI_Z0221]as t2 on t.DocEntry=t2.DocEntry where t.U_OrderId='{$orderId}'  ORDER BY t.DocEntry DESC ";
        }
       
        //查询售前
        if(I('fmjson')){
            $preSql = "SELECT TOP 1000 t.U_Suggest, t.DocEntry,t2.U_ProSts, U_AccuName ,U_ItemCode ,U_ItemName ,U_AccuDate ,U_AccuTime ,U_Phone ,U_Cstname ,U_AccuQDtl ,U_Address ,U_Qsummary ,U_Memo ,U_UserCode ,U_UserName  ,U_ProEndDate,U_ProEndTime ,U_AccuQDt2,U_Dealer,U_DealerName from [@TI_Z0220] as t  INNER JOIN [@TI_Z0221]as t2 on t.DocEntry=t2.DocEntry where 1=1  ";
            
          
            $whereData = json_decode(I('fmjson'),1);
            if($whereData['orderId']){
               $preSql.=  " and t.U_OrderId like '%{$whereData['orderId']}%'";
            }
            
            if($whereData['U_CardName']){
                $preSql.=  " and U_CardName like '%{$whereData['U_CardName']}%'";
            }
            
            if($whereData['U_Cstname']){
                $preSql.=  " and t.U_Cstname like '%{$whereData['U_Cstname']}%'";
            }
            
            if($whereData['U_Phone']){
                $preSql.=  " and t.U_Phone like '%{$whereData['U_Phone']}%'";
            }
            
            if($whereData['U_CardCode']){
                $preSql.=  " and t.U_CardCode like '%{$whereData['U_CardCode']}%'";
            }
            $preSql.=' ORDER BY t.DocEntry DESC';
         
            $preSql=iconv("utf-8","gb2312",$preSql);
            
        }
        $predata= $db->query($preSql);
        $return = array('fmData'=>@$data[0],'preData'=>$predata);
       
      //  error_log(var_export($return,1));
        echo json_encode($return,JSON_UNESCAPED_UNICODE);exit;
   
    }
   
    function getOrderAjax(){
        $this->initialize();
        $orderId = I('orderId');
        $sql = "SELECT U_Phone,U_Cstname,U_address FROM  [@TI_Z0081]as t where t.U_OrderId='{$orderId}'";
        $db = new \Sqlserver();
        $db->connent();
        
        $data= $db->query($sql);
        //error_log(var_export($data,1));
        echo json_encode($data[0],JSON_UNESCAPED_UNICODE);exit;
        
    }
    
    
    
    function updatePreAjax(){
        $this->initialize();
         $postData = I('data');
        $rowData = json_decode($postData,1);
        $fmdata = I('fmdata');
        $fmdata = json_decode($fmdata,1);  
        $data = $this->formatData($rowData, $fmdata);
        
        $docEntry = $rowData['DocEntry']; 
        $data_220=$data['data220'];
        $sql_220 = "update [@TI_Z0220] set ";
        $keys = array_keys($data_220);
        foreach ($keys as $value){
            $sql_220.= $value.' = '."'{$data_220[$value]}' ,";
        }
        $sql_220 = substr($sql_220, 0,strlen($sql_220)-1);
        
        $sql_220 = $sql_220."  where DocEntry={$docEntry}";
        $sql_220= iconv("utf-8","gb2312",$sql_220);
        
        $data_221=$data['data221'];
        $sql_221 = "update [@TI_Z0221] set ";
        $keys = array_keys($data_221);
        foreach ($keys as $value){
            $sql_221.= $value.' = '."'{$data_221[$value]}' ,";
        }
        $sql_221 = substr($sql_221, 0,strlen($sql_221)-1);
        $sql_221 = $sql_221."  where DocEntry={$docEntry}";
        $sql_221= iconv("utf-8","gb2312",$sql_221);
        $db = new \Sqlserver();
        $db->connent();
        $res= $db->saveBysql($sql_220);
        $res= $db->saveBysql($sql_221);
        $db->close();
        echo $res;
    }
    
    
    function savePreAjax(){
        $this->initialize();
        $postData = I('data');
        $rowData = json_decode($postData,1);
        $fmdata = I('fmdata');
        $fmdata = json_decode($fmdata,1);
        
        $data = $this->formatData($rowData, $fmdata);
        
        //添加0220
       // $keys = array('U_Address' , 'U_phone','U_OrderId','U_CardName','U_cstName','U_CardCode');
        $docEntry =  $this->getDocEntry('TI_Z0220');
        $data_220=$data['data220'];
        $data_220['DocEntry'] = $docEntry;
        $data_220['DocNum'] =$docEntry;
        $data_221=$data['data221'];
        $data_221['DocEntry'] = $docEntry;
       
        $kes = implode(',', array_keys($data_220));
        $values = "'".implode("','",$data_220)."'";
        $values= iconv("utf-8","gb2312",$values);
        $sql_220 = "insert into [@TI_Z0220] ({$kes}) VALUES ({$values});";
        $db = new \Sqlserver();
        $db->connent();
        //error_log($sql_220);
        $res= $db->saveBysql($sql_220);
        $kes = implode(',', array_keys($data_221));
        $values = "'".implode("','",$data_221)."'";
        $values= iconv("utf-8","gb2312",$values);
        $sql_221 = "insert into [@TI_Z0221] ({$kes}) VALUES ({$values});";
        $res= $db->saveBysql($sql_221);
        //$this->updateNextNumber('TI_Z0220');
        echo $res;
        exit;
        
    }
    
    /**
     * 获取客户列表
     */
    function getOCRD($type,$key){
       
        $this->initialize();
      $sql=  "select u_cardcode as id ,U_CardName  as text from [@ti_Z0070] WHERE 1=1  ";
      
      if($type==1&&$key){
          $sql.=" and u_cardcode like '%{$key}%'";
      }
      if($type==2&&$key){
          $sql.=" and U_CardName like '%{$key}%'";
      }
      $sql= iconv("utf-8","gb2312",$sql);
      $db = new Sqlserver();
      $db->connent();
      $data = $db->query($sql);
      return json_encode($data,JSON_UNESCAPED_UNICODE);
      
      
    }
    
    function getOCRDByCode_Auth(){
        $key = I('key');
        $data =json_decode($this->getOCRD(1, $key));
     
        $array= array(array('id'=>'*','text'=>'所有平台'),array('id'=>'*_1','text'=>'所有积分类平台'),array('id'=>'*_2','text'=>'所有分期类平台'));
        foreach ($data  as $item){
           array_push($array, $item); 
        }
        
        echo json_encode($array,JSON_UNESCAPED_UNICODE);
    
    }
    
    function getOCRDByName_Auth(){
        $key = I('key');
        
        $data =json_decode($this->getOCRD(2, $key));
         
        $array= array(array('id'=>'*','text'=>'所有平台'),array('id'=>'*_1','text'=>'所有积分类平台'),array('id'=>'*_2','text'=>'所有分期类平台'));
        foreach ($data  as $item){
            array_push($array, $item);
        }
        
        
          echo json_encode($array,JSON_UNESCAPED_UNICODE);
    
    }
    
    
    function getOCRDByCode(){
        $key = I('key');
       echo $this->getOCRD(1, $key);
        
    }
    
    function getOCRDByName(){
        $key = I('key');
        echo $this->getOCRD(2, $key);
    
    }
    
    
    function formatData($rowData,$fmdata){
        $date = date('Y-m-d',time());
        $time = date('Hi',time());
        $pid = $this->getPeriod();
        $data_220= array(
            'U_Address'=>$rowData['U_Address'],
            'U_phone'=>$rowData['U_Phone'],
            'U_OrderId'=>$fmdata['orderId'],
            'U_CardName'=>$fmdata['U_CardName'],
            'U_cstName'=>$fmdata['U_Cstname'],
            'U_CardCode'=>$fmdata['U_CardCode'],
            'Period'=>$pid,
            'Object' =>'TI_Z0220',
            'CreateDate'=>$date,
            'CreateTime'=>$time,
            'UpdateDate'=>$date,
            'UpdateTime'=>$time,
            'U_LastDate'=>$date,
            'U_Suggest'=>$rowData['U_Suggest']
        );
        
        $data_221 = array(
            'LineId' =>1,
            'VisOrder'=>0,
            'Object' =>'TI_Z0220',
            'U_AccuName'=>$rowData['U_AccuName'],
            'U_AccuDate'=>$date,
            'U_AccuTime'=>$time,
            'U_AccuTel'=>$rowData['U_Phone'],
            'U_AccuQDtl'=>$rowData['U_AccuQDtl'],
            'U_AccuPers'=>$fmdata['U_Cstname'],
            'U_CustAdr'=>$rowData['U_Address'],
            'U_Qsummary'=>$rowData['U_Qsummary'],
            'U_ItemCode'=>$rowData['U_ItemCode'],
            'U_ItemName'=>$rowData['U_ItemName'],
            'U_UserCode'=>$rowData['U_UserCode'],
            'U_UserName'=>$rowData['U_UserName'],
            'U_ProSts'=>$rowData['U_ProSts']?:1,
            'U_Memo'=>$rowData['U_Memo'],
            'U_Dealer'=>$rowData['U_Dealer'],
            'U_DealerName'=>$rowData['U_DealerName'],
            'U_AccuQDt2'=>$rowData['U_AccuQDt2'],
        );
        
        if($rowData['U_ProSts']==3){
            $data_221['U_ProEndTime']=$time;
            $data_221['U_ProEndDate']=$date;
            $data_221['VisOrder']=1;
        }
        return array('data221'=>$data_221,'data220'=>$data_220);
        
    }
    
    
    function formatData_Cust($rowData,$fmdata){
        $date = date('Y-m-d',time());
        $time = date('Hi',time());
        $pid = $this->getPeriod();  
        $data_210= array(
            'U_Address'=>$rowData['U_address'],
            'U_phone'=>$rowData['U_AccuTel'],
            'U_OrderId'=>$fmdata['orderId'],
            'U_CardName'=>$fmdata['U_CardName'],
            'U_cstName'=>$fmdata['U_Cstname'],
            'U_CardCode'=>$fmdata['U_CardCode'],
            'Object' =>'TI_Z0210',
            'Period'=>$pid,
            'CreateDate'=>$date,
            'CreateTime'=>$time,
            'UpdateDate'=>$date,
            'UpdateTime'=>$time,
            'U_LastDate'=>$date,
            'U_AlloStatus'=>$rowData['U_AlloStatus'],
            'U_Address'=>$rowData['U_CustAdr'],
        );
    
        $data_212 = array(
            'LineId' =>1,
            'VisOrder'=>0,
            'Object' =>'TI_Z0210',
            'U_AccuName'=>$rowData['U_AccuName'],
            'U_AccuDate'=>$date,
            'U_AccuTime'=>$time,
            'U_AccuTel'=>$rowData['U_AccuTel'],
            'U_AccuQDtl'=>$rowData['U_AccuQDtl'],
            'U_AccuDetl'=>$rowData['U_AccuDetl'],
            'U_AccuPers'=>$fmdata['U_Cstname'],
            'U_CustAdr'=>$rowData['U_address'],
            'U_QSummary'=>$rowData['U_QSummary'],
            'U_ItemCode'=>$rowData['U_ItemCode'],
            'U_ItemName'=>$rowData['U_ItemName'],
            'U_ProSts'=>$rowData['U_ProSts']?:1,
            'U_Memo'=>$rowData['U_Memo'],
            'U_Dealer'=>$rowData['U_Dealer'],
            'U_DealerName'=>$rowData['U_DealerName'],
            'U_Priority'=>$rowData['U_Priority'],
            'U_AccuQCLs'=>$rowData['U_AccuQCLs'],
            'U_CustAdr'=>$rowData['U_CustAdr'],
            'U_AlloStatus'=>$rowData['U_AlloStatus'],
        );
    
        if($rowData['U_ProSts']==3){
            $data_212['U_ProEndTime']=$time;
            $data_212['U_ProEndDate']=$date;
            $data_212['VisOrder']=1;
        }
    
        return array('data212'=>$data_212,'data210'=>$data_210);
    
    }
    
    function getDocEntry($table){
        
        $sql = "SELECT  top 1 DocEntry from [@{$table}] order by DocEntry desc";
        $db = new \Sqlserver();
        $db->connent();
        $data= $db->query($sql);
        $entry = $data[0]['DocEntry']+1;
        $entry=$entry>1000000?:1000000;
        return $entry;
    }
    
    function getPeriod(){
        $date =date('Y-m');
        $sql = "SELECT top 1 AbsEntry from OFPR WHERE Code='{$date}'";
        $db = new \Sqlserver();
        $db->connent();
        $data= $db->query($sql);
        return $data[0]['AbsEntry'];
    }
    
    function updateNextNumber($table){
        $sql = "UPDATE  NNM1 SET NextNumber=NextNumber+1    where ObjectCode = '{$table}' ";
        $db = new \Sqlserver();
        $db->connent();
        $res = $db->saveBysql($sql);

        return $res;
        
    }
    
    function initialize() {
        require 'Application/Home/ORG/Util/Sqlserver.class.php';
    }
  
    
    
    /**
     * 售后
     */
    function getCustdataAjax(){
        $this->initialize();
        $orderId = I('orderId');
        $sql = "SELECT
        CAST (
        ROW_NUMBER () OVER (ORDER BY t10.U_DocDate) AS nvarchar
        ) LineId,
        t10.*
        FROM
        (
        SELECT DISTINCT
        t10.U_CardCode,
        t10.U_CardName,
        t11.U_OrderId,
        t11.U_Cstname,
        t11.U_Phone,
        t11.U_DocDate,
        t11.U_ItemCode,
        t11.U_ItemName,
        t11.U_CitemCd,
        t11.U_CitemNm,
        t11.U_Color,
        t11.U_Address,
        t11.U_City,
        t11.U_Type
        FROM
        [@TI_Z0080] t10
        INNER JOIN [@TI_Z0081] t11 ON t10.DocEntry = t11.DocEntry
        WHERE
        t11.U_OStatus <> '5'
        AND t11.U_OrderId LIKE '%{$orderId}%'
        ) t10";
    
        $db = new \Sqlserver();
        $db->connent();
        if(!I('fmjson')){
            $data= $db->query($sql);
            $custSql = "SELECT TOP 10 t.U_AlloStatus, t.DocEntry, t2.U_BsEntry,t2.U_ItemCode,t2.U_ItemName,t2.U_Dealer,t2.U_DealerName,t2.U_AlloStatus,t2.U_Priority,t2.U_AccuName,t2.U_AccuQCLs,t2.U_AccuDate,t2.U_AccuTime,t2.U_AccuTel,t2.U_AccuPers,t2.U_AccuDetl,t2.U_AccuQDtl,t2.U_CustAdr,t2.U_QSummary,t2.U_ProSts,t2.U_ProEndDate,t2.U_ProEndTime from [@TI_Z0210] as t  INNER JOIN [@TI_Z0212]as t2 on t.DocEntry=t2.DocEntry where t.U_OrderId='{$orderId}'  ORDER BY t.DocEntry DESC ";
            
        }
        //售后信息
      
       
        if(I('fmjson')){
            $custSql = "SELECT TOP 1000 t.U_AlloStatus, t.DocEntry, t2.U_BsEntry,t2.U_ItemCode,t2.U_ItemName,t2.U_Dealer,t2.U_DealerName,t2.U_AlloStatus,t2.U_Priority,t2.U_AccuName,t2.U_AccuQCLs,t2.U_AccuDate,t2.U_AccuTime,t2.U_AccuTel,t2.U_AccuPers,t2.U_AccuDetl,t2.U_AccuQDtl,t2.U_CustAdr,t2.U_QSummary,t2.U_ProSts,t2.U_ProEndDate,t2.U_ProEndTime from [@TI_Z0210] as t  INNER JOIN [@TI_Z0212]as t2 on t.DocEntry=t2.DocEntry  where 1=1  ";
        
        
            $whereData = json_decode(I('fmjson'),1);
            if($whereData['orderId']){
                $custSql.=  " and t.U_OrderId like '%{$whereData['orderId']}%'";
            }
        
            if($whereData['U_CardName']){
                $custSql.=  " and U_CardName like '%{$whereData['U_CardName']}%'";
            }
        
            if($whereData['U_Cstname']){
                $custSql.=  " and t.U_Cstname like '%{$whereData['U_Cstname']}%'";
            }
        
            if($whereData['U_Phone']){
                $custSql.=  " and t.U_Phone like '%{$whereData['U_Phone']}%'";
            }
        
            if($whereData['U_CardCode']){
                $custSql.=  " and t.U_CardCode like '%{$whereData['U_CardCode']}%'";
            }
            $custSql.=' ORDER BY t.DocEntry DESC';
             error_log($custSql);
            $custSql=iconv("utf-8","gb2312",$custSql);
        
        }
        
        $predata= $db->query($custSql);
        
        $return = array('fmData'=>@$data[0],'preData'=>$predata);
    
        //  error_log(var_export($return,1));
        echo json_encode($return,JSON_UNESCAPED_UNICODE);exit;
         
    }
    
    function saveCustAjax(){
        $this->initialize();
        $postData = I('data');
        $rowData = json_decode($postData,1);
        $fmdata = I('fmdata');
        $fmdata = json_decode($fmdata,1);
    
        $data = $this->formatData_Cust($rowData, $fmdata);
        echo $this->saveCustomer($data['data210'], $data['data212']);
        
    }
    
    /**
     * 更新售后信息
     */
    function updateCustAjax(){
        $this->initialize();
        $postData = I('data');
        $rowData = json_decode($postData,1);
        $fmdata = I('fmdata');
        $fmdata = json_decode($fmdata,1);
        $data = $this->formatData_Cust($rowData, $fmdata);
    
        $docEntry = $rowData['DocEntry'];
        $data_210=$data['data210'];
        $sql_210 = "update [@TI_Z0210] set ";
        $keys = array_keys($data_210);
        foreach ($keys as $value){
            $sql_210.= $value.' = '."'{$data_210[$value]}' ,";
        }
        $sql_210 = substr($sql_210, 0,strlen($sql_210)-1);
    
        $sql_210 = $sql_210."  where DocEntry={$docEntry}";
        $sql_210= iconv("utf-8","gb2312",$sql_210);
    
        $data_212=$data['data212'];
        $sql_212 = "update [@TI_Z0212] set ";
        $keys = array_keys($data_212);
        foreach ($keys as $value){
            $sql_212.= $value.' = '."'{$data_212[$value]}' ,";
        }
        $sql_212 = substr($sql_212, 0,strlen($sql_212)-1);
        $sql_212 = $sql_212."  where DocEntry={$docEntry}";
        $sql_212= iconv("utf-8","gb2312",$sql_212);
        $db = new \Sqlserver();
        $db->connent();
         
        $res= $db->saveBysql($sql_210);
        $res= $db->saveBysql($sql_212);
        $db->close();
        echo $res;
    }
    
    /**
     * 添加售后信息
     */
    function saveCustomer($data_210,$data_212){
         //210 212
        $data_221['U_ProSts']=1;
      
        $docEntry =  $this->getDocEntry('TI_Z0210');
       
        $data_210['DocEntry'] = $docEntry;
        $data_210['DocNum'] =$docEntry;
        $data_212['DocEntry'] = $docEntry;
        
        $kes = implode(',', array_keys($data_210));
        $values = "'".implode("','",$data_210)."'";
        $values= iconv("utf-8","gb2312",$values);
        $sql_210 = "insert into [@TI_Z0210] ({$kes}) VALUES ({$values});";
        $db = new \Sqlserver();
        $db->connent();
       //error_log($sql_210);
        $res= $db->saveBysql($sql_210);
        $kes = implode(',', array_keys($data_212));
        $values = "'".implode("','",$data_212)."'";
        $values= iconv("utf-8","gb2312",$values);
        $sql_212 = "insert into [@TI_Z0212] ({$kes}) VALUES ({$values});";
        //error_log($sql_212);
        $res= $db->saveBysql($sql_212);
        //$this->updateNextNumber('TI_Z0210');
       return $res;
    }

    
    
    function querypresale(){
    
        $this->assign('src', '/sap/query_pre_sale.php');
        $this->display('report/index');
    }
    
    function addpresale(){
        $this->assign('src', 'sap/pre_sale.php');
        $this->display('report/index');
    }
    
    function querycust(){
        $this->assign('src', 'sap/query_cust_sale.php');
        $this->display('report/index');
    }
    
    function addcust(){
        $this->assign('src', 'sap/cust_sale.php');
        $this->display('report/index');
    }
    
       function mycustOrder(){
        $this->assign('src', 'sap/my_cust_order.php');
        $this->display('report/index');
    }
    
    function mycustOrderAjax(){
        
        $datastr = I('data');
        $data = json_decode($datastr,1);
        $where = 'where 1 = 1 ';
        if($data['CreateDate1']){
            $where.="and t.CreateDate>='{$data['CreateDate1']}' ";
            unset($data['CreateDate1']);
        }else{
            unset($data['CreateDate1']);
        }
        
        if($data['CreateDate2']){
            $where.="and t.CreateDate<='{$data['CreateDate2']}' ";
            unset($data['CreateDate2']);
        }else{
            unset($data['CreateDate2']);
        }
        
        foreach ($data as $key=>$value){
            
              if($value){
                  $where.=' and t.'.$key."like '%{$value}%'";
              }
        }

        $custSql = "SELECT  top 100 T.U_OrderId,t.U_Priority, t.U_Cardcode,t.U_CardName, t.U_AlloStatus, t.DocEntry, t2.U_BsEntry,t2.U_ItemCode,t2.U_ItemName,t2.U_Dealer,t2.U_DealerName,t2.U_AlloStatus,t2.U_Priority,t2.U_AccuName,t2.U_AccuQCLs,t2.U_AccuDate,t2.U_AccuTime,t2.U_AccuTel,t2.U_AccuPers,t2.U_AccuDetl,t2.U_AccuQDtl,t2.U_CustAdr,t2.U_QSummary,t2.U_ProSts,t2.U_ProEndDate,t2.U_ProEndTime from [@TI_Z0210] as t  INNER JOIN [@TI_Z0212]as t2 on t.DocEntry=t2.DocEntry {$where}  ORDER BY t.DocEntry DESC ";
        $this->initialize();
        $db = new \Sqlserver();
        $db->connent();
        $result = $db->query($custSql);
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
        exit;
    }

    public function index()
    {
        $this->display('Report/index');
    }

    public function salesOrderIndex()
    {

        $key = I('keyword');
        $type = I('eq_type');
        $map=[];
        $user  = session('user_name');
        if($type=='-8'){
            $map['concat(stock_process,user)'] = array('like',  '%' . trim($user) . '%');
        }
        else
            $map['concat(to_user,user)'] = array('like',  '%' . trim($user) . '%');

        if(isset($_POST['type'])||$type){
            if($type!='-8')
                $map['status'] = array('eq', $type);
        }else{
            $map['status'] = array('eq', 1);
        }

        if($key){
            $map['concat(name,sap_code,suppliers_name)'] = array('like',  '%' . trim($key) . '%');
        }
        $model = M("projectJicai");
        $this->assign('curr_user',session('user_name'));
        $this->assign('keyword',$key);
        $this->assign('status',$type?:1);
        $res= $this -> _list($model, $map, 'id desc');
        $this->display();

    }

    public function salesOrderAdd()
    {
        $this->display();
    }

    private $reviewstep = array('wendy.li','Tony'); //单据审核流程

    function doSalesOrderAdd(){
        $respons = array('code'=>0,'msg'=>'操作成功!');
        $post = $_POST['data'];
        $type = I('type');
        $cp   = I('cp');
        $sale = I('sale');
        $suppliers_code = I('gys_code');
        $suppliers_name= I('gys_name');
        $remarkes = I('remarkes');
        $storage_time = I('storage_time');
        $receipter = I('receipter');
        $receipterCode = I('receipterCode');

        // 2017-07-24 验证供应商信息
        if($suppliers_code == $suppliers_name)
        {
            $respons['code']=-1;
            $respons['msg']='供应商信息错误！请使用系统提供的供应商查询功能！';
            echo json_encode($respons);
            exit ;
        }

        if(strtotime($storage_time)<time()){
            $respons['code']=-1;
            $respons['msg']='到货时间错误';
            echo json_encode($respons);
            exit ;
        }

        $id   = I('id');
        if(!$post){
            $respons['code']=-1;
            $respons['msg']='数据错误';
            echo json_encode($respons);
            exit ;
        }
        $model = D("projectJicai");
        $infoModel = D("projectJicaiInfo");
        $saveData = json_decode($post,true);
        foreach ($saveData as $key=>$vo){
            $ckeck =$this->_checkItemWHCode($vo['item_code'], $vo['warehouse']);
            error_log($ckeck);
            if(!$ckeck){
                $respons['code']=-1;
                $respons['msg']=$vo['item_code'].' 仓库选择错误,请修改';
                echo json_encode($respons);
                exit ;
            }
        }
        $total = array_sum(array_column($saveData, 'amout')); //备货物料总数量
        $totalPrice = array_sum(array_column($saveData, 'total_price')); //备货物料总价
        $user = session('user_name');
        $name = $user.'-'.time();
        $stock_process = array();
        $stock_process[] =$cp;

        /**
         * 插入 修改 之前判断是否可以自动审核功能
         * form 提交数据 $saveData
         */
        $runProcessTag = 0; // 0 : 不需要审批(默认), 1 : 要审批
        $items = array();
        $nowTime = date('Y-m-d H:i:s');
        $yesterdayTime = date('Y-m-d H:i:s',strtotime('-1 day'));

        // 2017-09-04 根据提交的组长ID查找主管ID，并拼接审批流
        $productManagerModel = M('productManager');
        $captains = $productManagerModel->where("emp_no = '{$cp}'")->find();
        if(!empty($captains['captain_no'])) {
            $stock_process[] = $captains['captain_no'];
        }
//        foreach ($captains as $cpKey => $cpValue)
//        {
//            $stock_process[] = $cpValue['captain_no'];
//        }

        if($sale)
            $stock_process[] =$sale;
        if($total>=1000||$totalPrice>=50000){
            $stock_process =  array_merge($stock_process,$this->reviewstep);
            $runProcessTag = 1;
        }else{
            $stock_process[] = $this->reviewstep[0];
        }

        // 1. 必须是常规备货 $type == 3
        if ($type == 3) {
            foreach ($saveData as $key => $value){
                $itemCode = $value['item_code'];
                $itmeInformation = $this->_getItemInfo($itemCode);
                $suppliersCode = $value['suppliers_code'];

                // 0. 第一次采购必审批
                if ($itmeInformation['previous_price'] == 0)
                {
                    // must
                    //var_dump('must 01');
                    $runProcessTag = 1;
                    //break;
                }

                // 3. by 物料 判定条件: 小于等于上次采购价格.
                if ($value['p_price']>$itmeInformation['previous_price'])
                {
                    // must
                    //var_dump('must 02');
                    $runProcessTag = 1;
                }

                $items[$itemCode]['available_inventory'] = $itmeInformation['available_inventory']; //可用库存数量available_inventory
                $items[$itemCode]['r_inventory'] = $itmeInformation['r_inventory']; //安全库存
            }

//             2. by 物料 判定条件: 本次采购数量amout(post)+可用库存数量available_inventory(last code)+以当前时间为基准前溯过去24内订单数量总和sql 小于等于安全库存r_inventory(last code).
            if($runProcessTag == 0){

                foreach ($saveData as $key => $value){
                    $itemCode = $value['item_code'];
                    $suppliersCode = $value['suppliers_code'];
                    $itemAmount = $value['amout']; //本次采购数量amout

                    //使用缓存数据 $items
                    //查询think_stocking_info表中数据并判断
                    //think_stocking_info表中创建新字段 ALTER TABLE `think_stocking_info` ADD `ctime` DATETIME NOT NULL COMMENT '创建时间' AFTER `sap_status`;

                    $model_info = D("projectJicaiInfo");
                    $sqlforItem  = "SELECT SUM(amout) as itemAmount, SUM(total_price) as itemTotalValue FROM `think_stocking_info` WHERE suppliers_code = '{$suppliersCode}' AND item_code = '{$itemCode}' and ctime BETWEEN '{$yesterdayTime}' AND '{$nowTime}'";
                    $result = $model_info->query($sqlforItem);
                    if (empty($result[0])){
                    }else{
                        $lastDatabyItemAndsuppliers = $result[0];
                        $tmpItemAmount = $itemAmount + $items[$itemCode]['available_inventory']+ $lastDatabyItemAndsuppliers['itemAmount'] ;
                        if($tmpItemAmount > $items[$itemCode]['r_inventory']){
                            // must
                            //var_dump('must 03');
                            $runProcessTag = 1;
                            break;
                        }
                    }

                    //20170523添加新判断规则: 如果备货数量<本次采购数量=$value['amout']>大于建议备货数量<$value['suggestorder']>时，则触发审批!by物料
                    $suggestOrder = $value['suggestorder'];
                    if ($itemAmount > $suggestOrder){
                        $runProcessTag = 1;
                        break;
                    }

                    //框架工作模式
                    //$model = D('StockingInfo');
                    //$data = $model->where("suppliers_code={$suppliersCode}","item_code={$itemCode}")->select();

                }

            }

            // 4. by 供应商 判定条件: 计算包括本次订单在内的，以当前时间为基准前溯过去24小时内，该供应商的订单总金额不超过5万，且货品总数量不超过1000个.
            if($runProcessTag == 0){
                $model = D("projectJicai");
                $sqlforTotal  = "SELECT SUM(item_count) as itemTotal, SUM(price_total) as totalValue FROM `think_stocking` WHERE suppliers_code = '{$suppliersCode}' and ctime BETWEEN '{$yesterdayTime}' AND '{$nowTime}'";
                $result = $model->query($sqlforTotal);
                if (empty($result[0])){
                    // 2017-07-24 向前回退24小时没有满足触发条件的数据，但是当前订单数量，金额都已超限的情况。 $runProcessTag = 1;

                }else{
                    $lastDatabySuppliers = $result[0];
                    if ($lastDatabySuppliers['itemTotal'] > 1000 || $lastDatabySuppliers['totalValue'] > 50000){
                        //var_dump('must 04');
                        $runProcessTag = 1;
                    }
                }
            }

        }
        else{
            $runProcessTag = 1;
        }

        // 2017-10-17 新审批需求加入 Mario -->
        if($runProcessTag == 1)
        {
            $howManyApprove = count($stock_process);
            // wendy.li : must
            if ($stock_process[$howManyApprove-1]=='wendy.li' || $stock_process[$howManyApprove-2]=='wendy.li'){
                $positionKind = 0; //1:无Tony, 2:有Tony.
                $addMarioTag = 0;
                $mario = "mario.wu";
                if($stock_process[$howManyApprove-1]=='wendy.li') {$positionKind = 1;}
                if($stock_process[$howManyApprove-2]=='wendy.li') {$positionKind = 2;}

                // 备货类型: $type 类型 1集采 2非常规  3常规
                //check items...
                foreach ($saveData as $key => $value){

                    if($type != 1){

                        if($value['taotal_sales'] == 0)
                        {
                            $addMarioTag = 1;
                            break;
                        }

                        if($type == 3){
                            if($value['amout'] > $value['lately_7']){
                                $addMarioTag = 1;
                                break;
                            }
                        }elseif ($type == 2){
                            if ($value['amout'] > $value['lately_15']){
                                $addMarioTag = 1;
                                break;
                            }
                        }
                    }
                }

                if($addMarioTag == 1)
                {
                    // update the process list
                    switch($positionKind)
                    {
                        case 1:
                            array_push($stock_process,$mario);
                            break;
                        case 2:
                            $tmpArray = array_splice($stock_process, $howManyApprove-1, 0, $mario);
                            break;
                        default:
                            break;
                    }
                    if(!empty($tmpArray))
                    {$stock_process = $tmpArray;}

                }
            }
        }
        // <-- 2017-10-17 新审批需求加入 Mario

        if($id){
            //do update
            $where = "stocking_id={$id}";
            $stData = array('receipterCode'=>$receipterCode, 'receipter'=>$receipter,'user'=>$user,'to_user'=>$stock_process[0],'item_count'=>$total,'price_total'=>$totalPrice,'remarkes'=>$remarkes,'suppliers_code'=>$suppliers_code,'suppliers_name'=>$suppliers_name,'type'=>$type,'stock_process'=>json_encode($stock_process,JSON_UNESCAPED_UNICODE),'storage_time'=>$storage_time);
            $model->where($where)->save($stData);
            $this->_saveLog(array('stocking_id'=>$id,'user'=>$user,'info'=>'修改'));
            $infoModel->where($where)->delete();

        }else{
            //do add
            //$stData = array('receipterCode'=>$receipterCode, 'receipter'=>$receipter,'name'=>$name,'ctime'=>date('Y-m-d H:i:s'),'user'=>$user,'to_user'=>$stock_process[0],'step'=>0,'item_count'=>$total,'price_total'=>$totalPrice,'remarkes'=>$remarkes,'suppliers_code'=>$suppliers_code,'suppliers_name'=>$suppliers_name,'type'=>$type,'stock_process'=>json_encode($stock_process,JSON_UNESCAPED_UNICODE),'manager'=>$cp,'sale'=>$sale,'storage_time'=>$storage_time);
            //var_dump($runProcessTag);die();
            if ($runProcessTag == 0)
            {
                // status = 2
                // to_user = ''
                $stData = array('status'=>'2','receipterCode'=>$receipterCode, 'receipter'=>$receipter,'name'=>$name,'ctime'=>$nowTime,'user'=>$user,'to_user'=>$stock_process[0],'step'=>0,'item_count'=>$total,'price_total'=>$totalPrice,'remarkes'=>$remarkes,'suppliers_code'=>$suppliers_code,'suppliers_name'=>$suppliers_name,'type'=>$type,'stock_process'=>json_encode($stock_process,JSON_UNESCAPED_UNICODE),'manager'=>$cp,'sale'=>$sale,'storage_time'=>$storage_time);
            }else {
                $stData = array('receipterCode' => $receipterCode, 'receipter' => $receipter, 'name' => $name, 'ctime' => $nowTime, 'user' => $user, 'to_user' => $stock_process[0], 'step' => 0, 'item_count' => $total, 'price_total' => $totalPrice, 'remarkes' => $remarkes, 'suppliers_code' => $suppliers_code, 'suppliers_name' => $suppliers_name, 'type' => $type, 'stock_process' => json_encode($stock_process, JSON_UNESCAPED_UNICODE), 'manager' => $cp, 'sale' => $sale, 'storage_time' => $storage_time);
            }

            $id = $model->add($stData);

            if ($runProcessTag == 0)
            {
                $this->_saveLog(array('stocking_id'=>$id,'user'=>$user,'info'=>'创建,并自动通过审核.'));
            }else {
                $this->_saveLog(array('stocking_id' => $id, 'user' => $user, 'info' => '创建'));
            }
            //$this->sendEmail($stock_process[0].'@g-town.com.cn', "有新的备货申请单等待您审核", "单号名称:{$name}<br/>物料总数:{$total}<br/>备货总价:{$totalPrice}<br/>申请人:{$user}");
            //weixinsendmsg("[有新的备货申请单等待您审核]", "单号名称:{$name}\n物料总数:{$total}\n备货总价:{$totalPrice}\n申请人:{$user} \n请及时登陆OA系统处理",$stock_process[0]);
        }

        /**
         * 添加物料明细
         */
        foreach ($saveData as $vo){
            unset($vo['id']);
            $vo['stocking_id']   = $id;
            $vo['storage_time']  = $storage_time;
            $vo['suppliers_name']= $suppliers_name;
            $vo['suppliers_code']= $suppliers_code;
            if (!empty($nowTime)){
                $vo['ctime']= $nowTime;
            }
            $infoModel->add($vo);
        }

        echo json_encode($respons);

    }

    /**
     * 检查物料选择的仓库有是否正确
     */
    function _checkItemWHCode($itemCode,$whcode){

        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $sql = "select whscode,whsname from ax_itemavailablewhs where itemcode='{$itemCode}' and whscode='{$whcode}'";
        //$sql = "select whscode,whsname from dummy_ItemAvailableWhs where itemcode='{$itemCode}' and whscode='{$whcode}'";
        $data = $sqlObj->query($sql);
        if($data)
            return true;
        else
            return false;

    }

    protected function _getItemInfo($code) {
        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $sql = "select itemcode, isnull(LastPurPrc,0) LastPurPrc  from oitm where itemcode='{$code}' ";
        $lastp_price = $sqlObj->query($sql)[0]['LastPurPrc'];
        $sql = "select itemcode,onhand current_inventory ,onorder transit_inventory,onhand+onorder-U_TI_Z0_IsCommited-U_TI_Z0_IsJp  available_inventory from oitw where whscode in ('HYWCK') and itemcode='{$code}'";
        $inventoryInfo =  $sqlObj->query($sql)[0];
        $sql = "SELECT [itemcode] ,[RsafeStock] r_inventory ,[Day7sales] lately_7 ,[Day15sales] lately_15 ,[Day30sales] lately_30 ,[Day365sales] taotal_sales,[suggestorder],[availableday],[avgbuyday],[avgdaliysale],[minsafe] FROM [dbo].[AX_SafeStockAndSalesCount] where itemcode='{$code}'";
        $saleInfo =  $sqlObj->query($sql)[0];
        $whouseSql  = "select whscode,whsname from ax_itemavailablewhs where itemcode='{$code}' order by whscode desc";
        $whouse =  $sqlObj->query($whouseSql)[0]['whscode'];
        $respons = array('warehouseCode'=>$whouse,'r_inventory'=>(int)$saleInfo['r_inventory'],'lately_15'=>(int)$saleInfo['lately_15'],'lately_30'=>(int)$saleInfo['lately_30'],'taotal_sales'=>(int)$saleInfo['taotal_sales'], 'previous_price'=>$lastp_price,'current_inventory'=>(int)$inventoryInfo['current_inventory'],'transit_inventory'=>(int)$inventoryInfo['transit_inventory'],'available_inventory'=>(int)$inventoryInfo['available_inventory'],'suggestorder'=>(int)$saleInfo['suggestorder'],'availableday'=>(int)$saleInfo['availableday'],'avgbuyday'=>(int)$saleInfo['avgbuyday'],'avgdaliysale'=>(int)$saleInfo['avgdaliysale'],'minsafe'=>(int)$saleInfo['minsafe']);
        return $respons;

    }

    /**
     * 保存操作日志
     * @param unknown $data
     * @return Ambigous <mixed, boolean, unknown, string>
     */
    function _saveLog($data = array()){
        return D('projectJicaiLog')->add(array('pid'=>$data['stocking_id'],'user'=>$data['user'],'info'=>$data['info'],'ctime'=>date('Y-m-d H:i:s'),'type'=>'jicai'));

    }

    function info(){
        $id = (int)I('id');
        $info = D('projectJicai')->where("id={$id}")->find();
        if($info){

            if(strtolower(session('user_name'))==strtolower($info['to_user'])){
                $this->assign('access',true);
            }

            if($info['status']==2||$info['status']==-1){
                $this->assign('access',false);
            }
        }
        $this->assign('log',D('projectJicaiLog')->where("pid={$id} and type='jicai'")->select());
        $this->assign('info',$info);
        $this->display();
    }

    function getinfo(){
        $id = (int)I('id');
        $model = D('projectJicaiInfo');
        $data = $model->where("stocking_id={$id}")->select();
        $data = array('total'=>count($data),'data'=>$data);
        echo json_encode($data);
        exit;
    }

    /**
     * 审核
     */
    function review(){
        $respons = array('code'=>0,'msg'=>'');
        $id = I('id');
        $status = I('status');
        $model =  D('projectJicai');
        $info =$model->where("id={$id}")->find();
        $reviewstep = json_decode($info['stock_process'],true);
        if($info['step']==count($reviewstep)-1){ //完结 最后一个审核
            if($status!=-1)
                $status = 2;
            $info['to_user'] = '';

        }else{
            $info['to_user'] = $reviewstep[$info['step']+1];
        }

        if($status==-1){
            $info['to_user'] = '';
        }
        $info['status'] = $status;
        $info['step']+=1; //当前审核步骤+1
        $remarkes = I('remarkes');
        $loginfo = $info['status']>=1?"同意":"否决";
        $this->_saveLog(array('stocking_id'=>$id,'user'=>session('user_name'),'info'=>$remarkes?$loginfo."  备注:".$remarkes:$loginfo));
        if($info['status']!=-1&&$info['status'] != 2&&$info['to_user']){
            //$this->sendEmail($info['to_user'].'@g-town.com.cn', "有新的备货申请单等待您审核", "单号名称:{$info['name']}<br/>物料总数:{$info['item_count']}<br/>备货总价:{$info['price_total']}<br/>申请人:{$info['user']}");
            //weixinsendmsg("[有新的备货申请单等待您审核]", "单号名称:{$info['name']}\n物料总数:{$info['item_count']}\n备货总价:{$info['price_total']}\n申请人:{$info['user']} \n请及时登陆OA系统处理",  $info['to_user']);
        }

        $model->where("id={$id}")->save($info);
        echo json_encode($respons);exit;


    }

    function delete(){
        $id = (int)I('id');
        $res =  D('projectJicai')->where("id={$id}")->delete();
        $res+=  D('projectJicaiInfo')->where("stocking_id={$id}")->delete();
        echo $res;exit;
    }

    function  clonedata(){
        $id = I('id');
        $list = D('projectJicaiInfo')->where("stocking_id={$id}")->select();
        $this->assign("data",json_encode($list,JSON_UNESCAPED_UNICODE));
        $info = D('projectJicai')->where("id={$id}")->find();
        $this->assign("info",$info);
        $this->display('salesOrderAdd');
    }

}